package online.chazi.netkit.annotation;

import lombok.extern.slf4j.Slf4j;
import online.chazi.netkit.action.Action;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-05-04 23:29
 */
@Slf4j
public abstract class SimpleInjectProxy implements InjectProxy {

    public abstract Object getBean(Class<?> type);

    public abstract Object getBean(String type);

    @Override
    public void inject(Action action) throws Exception {
        Inject classInject = action.getClass().getAnnotation(Inject.class);
        if (classInject != null) {

            if (!"".equals(classInject.name())) {
                log.warn("注解类时，指定name无效！");
            }

            for (Field field : action.getClass().getDeclaredFields()) {
                try {
                    if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue;
                    Object object = getBean(field.getType());
                    field.setAccessible(true);
                    field.set(action, object);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

        } else {

            for (Field field : action.getClass().getDeclaredFields()) {
                if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue;
                Inject inject = field.getAnnotation(Inject.class);
                if (inject != null) try {

                    String name = inject.name();
                    Object object;
                    if (!"".equals(name)) {
                        object = getBean(name);
                    } else {
                        object = getBean(field.getType());
                    }
                    field.setAccessible(true);
                    field.set(action, object);

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

        }
    }
}
